package com.ledim.fragment;

import android.os.Bundle;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import com.ledim.activity.FeedbackActivity;
import com.ledim.activity.GoneCardsActivity;
import com.ledim.activity.GoneRoomsActivity;
import com.ledim.activity.SettingActivity;
import com.ledim.activity.UserContributeActivity;
import com.ledim.activity.UserLoginActivity;
import com.ledim.bean.LedimUserBean;
import com.ledim.bean.UserSignDataBean;
import com.ledim.bean.base.BaseResultDataInfo;
import com.ledim.datastatistics.LeDimAnalysisUtils;
import com.ledim.fragment.base.LeDimBaseFragment;
import com.ledim.ledimview.LedimBaseUserInfoView;
import com.ledim.ledimview.LedimBaseUserPowerView;
import com.ledim.service.ApiService;
import com.ledim.service.LedimApiServiceFactory;
import com.ledim.service.LedimHttpObserver;
import com.ledim.service.coverter.LedimGsonConverterFactory;
import com.ledim.utils.ConstantUtil;
import com.ledim.utils.LedimNetWorkUtils;
import com.ledim.utils.LedimSpUtils;
import com.ledim.utils.LogUtil;
import com.ledim.utils.ToastUtil;
import com.letv.android.young.client.R;
import com.letv.tracker2.enums.EventType;
import com.letv.tracker2.enums.Key;
import java.util.HashMap;
import org.greenrobot.eventbus.Subscribe;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * 个人中心页
 */
public class LedimProfileFragment extends LeDimBaseFragment {

    private View mView;
    private LedimUserBean userData;
    private ScrollView mScrollView;
    private LedimBaseUserInfoView mBaseUserinfoView;
    private LedimBaseUserPowerView mBaseUserPowerView;
    private LinearLayout mUserUnLoginBg;
    private TextView mContribute;

    @Override
    protected void initContentView(View view, Bundle saveInstanceState) {
        initView(view);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.tab_profile;
    }

    private void reportExpose() {
        HashMap<String, String> params = new HashMap<String, String>();
        params.put(Key.Type.name(), "mine");
        LeDimAnalysisUtils.reportEvent(LeDimAnalysisUtils.MINE_PAGE_CODE, EventType.Expose, params);
    }

    @Override
    public void onResume() {
        super.onResume();
        if (!isHidden()) {
            reportExpose();
            //mScrollView回到顶部
            mScrollView.fullScroll(ScrollView.FOCUS_UP);
            setLoginState();
            //显示信息
            mBaseUserinfoView.showMsgInfo();
            //获取用户信息
            getUserInfo();
        }
    }

    private void initView(View mView) {
        //获取baseuserinfoview
        mBaseUserinfoView =
                (LedimBaseUserInfoView) mView.findViewById(R.id.ledim_base_userinfo_layout);
        mBaseUserinfoView.initSetting(this, false);

        //获取baseuserpowerview
        mBaseUserPowerView =
                (LedimBaseUserPowerView) mView.findViewById(R.id.ledim_base_userpower_layout);
        mBaseUserPowerView.initSetting(false);

        //登录
        Button mUserLogin = (Button) mView.findViewById(R.id.bt_user_login);
        mUserLogin.setOnClickListener(this);

        mUserUnLoginBg = (LinearLayout) mView.findViewById(R.id.ll_user_unlogin_bg);

        //设置观看历史和去过的放映厅反馈界面点击事件
        mView.findViewById(R.id.tv_setting).setOnClickListener(this);
        mView.findViewById(R.id.tv_history).setOnClickListener(this);
        mView.findViewById(R.id.tv_room).setOnClickListener(this);
        mView.findViewById(R.id.tv_feedback).setOnClickListener(this);
        mContribute = (TextView) mView.findViewById(R.id.tv_contribute);
        mContribute.setOnClickListener(this);
        mScrollView = (ScrollView) mView.findViewById(R.id.sv_myscrollview);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bt_user_login:
                //登录页面
                if (LedimNetWorkUtils.isNetworkAvailable(getActivity())) {
                    goToOthers(UserLoginActivity.class);
                    getActivity().overridePendingTransition(R.anim.push_buttom_in, R.anim.push_buttom_out);
                } else {
                    ToastUtil.toast(R.string.net_error);
                }
                break;
            case R.id.ll_user_sign:
                //签到页面
                userSign();
                break;
            case R.id.tv_setting:
                goToOthers(SettingActivity.class);
                getActivity().overridePendingTransition(R.anim.push_right_in, R.anim.push_right_out);
                break;
            case R.id.tv_history:
                //观看历史
                goToOthers(GoneCardsActivity.class);
                getActivity().overridePendingTransition(R.anim.push_right_in, R.anim.push_right_out);
                break;

            case R.id.tv_room:
                //去过的放映厅
                goToOthers(GoneRoomsActivity.class);
                getActivity().overridePendingTransition(R.anim.push_right_in, R.anim.push_right_out);
                break;

            case R.id.tv_feedback:
                goToOthers(FeedbackActivity.class);
                getActivity().overridePendingTransition(R.anim.push_right_in, R.anim.push_right_out);
                break;
            case R.id.tv_contribute:
                goToOthers(UserContributeActivity.class);
                getActivity().overridePendingTransition(R.anim.push_right_in, R.anim.push_right_out);
                break;
            default:
                break;
        }
    }

    /**
     * 用户签到
     */
    private void userSign() {
        LedimApiServiceFactory.createService(ApiService.class)
                              .userSign()
                              .observeOn(AndroidSchedulers.mainThread())
                              .subscribeOn(Schedulers.io())
                              .subscribe(new LedimHttpObserver<BaseResultDataInfo<UserSignDataBean>>() {
                                  @Override
                                  public void onCompleted() {
                                      super.onCompleted();
                                  }

                                  @Override
                                  public void onNext(
                                          BaseResultDataInfo<UserSignDataBean> userSignBean) {
                                      super.onNext(userSignBean);
                                      if (userSignBean != null) {
                                          if (userSignBean.success) {
                                              //成功
                                              mBaseUserinfoView.setSignInfo(userSignBean.data);
                                              //签到成功之后,也将其progressbar和金币刷新下
                                              if (!TextUtils.isEmpty(userSignBean.data.power) &&
                                                      !TextUtils.isEmpty(userSignBean.data.coin)) {
                                                  mBaseUserPowerView.getSwordAndShow(userSignBean.data.power);
                                                  mBaseUserPowerView.chooseGoldImage(userSignBean.data.coin, userSignBean.data.max_coin);
                                                  //开启签到动画
                                                  mBaseUserPowerView.startGoldLevelAnim();
                                              }
                                          } else {
                                              //失败
                                              ToastUtil.toast(userSignBean.message);
                                          }
                                      }

                                  }

                                  @Override
                                  public void onError(Throwable e) {
                                      super.onError(e);
                                      ToastUtil.toast(e.getMessage());
                                      LogUtil.e(e.getMessage());
                                  }
                              });
    }

    /**
     * 通过uid来获取用户信息
     */
    private void getUserInfo() {
        if (LedimSpUtils.isLogin()) {
            mContribute.setVisibility(View.VISIBLE);
            LedimApiServiceFactory.createService(ApiService.class)
                                  .getUserInfo()
                                  .observeOn(AndroidSchedulers.mainThread())
                                  .subscribeOn(Schedulers.io())
                                  .subscribe(new LedimHttpObserver<BaseResultDataInfo<LedimUserBean>>() {

                                      @Override
                                      public void onCompleted() {
                                          super.onCompleted();
                                      }

                                      @Override
                                      public void onError(Throwable e) {
                                          super.onError(e);
                                          LogUtil.e(e.getMessage());
                                      }

                                      @Override
                                      public void onNext(
                                              BaseResultDataInfo<LedimUserBean> userIdGetResponseBean) {
                                          if (userIdGetResponseBean != null) {
                                              if (userIdGetResponseBean.success) {
                                                  //成功
                                                  {
                                                      try {
                                                          userData = userIdGetResponseBean.data;
                                                          LedimSpUtils.setUser(LedimGsonConverterFactory
                                                                  .create().gson.toJson(userData));

                                                          //展示用户信息
                                                          mBaseUserinfoView.setUserInfo(userData);
                                                          mBaseUserPowerView.chooseGoldImage(userData.coin, userData.max_coin);
                                                          mBaseUserPowerView.getSwordAndShow(userData.power);
                                                      } catch (Exception e) {
                                                          e.printStackTrace();
                                                      }
                                                  }
                                              } else {
                                                  //失败
                                                  ToastUtil.toast(userIdGetResponseBean.message);
                                              }
                                          }
                                      }
                                  });

        } else {
            mContribute.setVisibility(View.GONE);
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            reportExpose();
            setLoginState();
            //显示信息
            mBaseUserinfoView.showMsgInfo();
            //获取用户信息
            getUserInfo();
            //mScrollView回到顶部
            mScrollView.fullScroll(ScrollView.FOCUS_UP);
        }
    }

    /**
     * 设置登录的状态
     */
    private void setLoginState() {
        if (!LedimSpUtils.isLogin()) {
            //未登录
            mUserUnLoginBg.setVisibility(View.VISIBLE);
            mBaseUserPowerView.setVisibility(View.GONE);
            mBaseUserinfoView.setLayoutInvisible();
            mBaseUserinfoView.setSignInvisible();

        } else {
            //已登录
            mUserUnLoginBg.setVisibility(View.GONE);
            mBaseUserPowerView.setVisibility(View.VISIBLE);
            mBaseUserinfoView.setLayoutVisible();

        }
    }

    @Subscribe
    public void onEvent(Message event) {
        if (mBaseUserinfoView != null && !isHidden() &&
                event.what == ConstantUtil.EventBusMsgConstant.PUSH_MSG_NOTICE) {
            mBaseUserinfoView.showMsgInfo();
        }
    }

    protected boolean useEventBus() {
        return true;
    }
}
